/*
 * Copyright 2016-2017 TVI Go Easy.
 * Created on 2017/5/9 14:34
 */
package org.mechanic.fund.web.wechat;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.mechanic.core.web.MediaTypes;
import org.mechanic.fund.service.wechat.IWcBaseInfoService;
import org.mechanic.fund.web.BaseController;
import org.mechanic.fund.web.system.LoginController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.MessageFormat;

/**
 * 微信相关 API
 *
 * @author mechanic
 * @version 0.0.1
 */
@Api("微信相关相关接口")
@RestController
public class WechatController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    private final IWcBaseInfoService baseInfoService;

    @Autowired
    public WechatController(IWcBaseInfoService baseInfoService) {this.baseInfoService = baseInfoService;}

    /**
     * 响应微信发送的Token验证。验证成功则输出echostr的值，不成功则输出"非法请求"。
     * 在服务号中填写地址：https://domainname/api/mp_token
     *
     * @param signature 微信加密签名。signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
     * @param echostr   随机字符串
     * @param timestamp 时间戳
     * @param nonce     随机数
     */
    @ApiOperation(value = "相应微信服务号发送的Token验证接口")
    @GetMapping(value = "mp_token", produces = MediaTypes.JSON_UTF_8)
    public void token(
      HttpServletResponse response,
      @ApiParam(value = "微信加密签名", required = true)
      @RequestParam(value = "signature", required = true) String signature,
      @ApiParam(value = "随机字符串", required = true)
      @RequestParam(value = "echostr", required = true) String echostr,
      @ApiParam(value = "时间戳", required = true)
      @RequestParam(value = "timestamp", required = true) String timestamp,
      @ApiParam(value = "随机数", required = true)
      @RequestParam(value = "nonce", required = true) String nonce
    ) throws IOException {
        logger.info("微信token验证开始.....");
        logger.info(MessageFormat.format("signature:{0}", signature));
        logger.info(MessageFormat.format("timestamp:{0}", timestamp));
        logger.info(MessageFormat.format("nonce:{0}", nonce));
        logger.info(MessageFormat.format("echostr:{0}", echostr));

        PrintWriter writer = response.getWriter();
        if (baseInfoService.isSignature(signature, timestamp, nonce)) {
            writer.print(echostr);
        } else {
            writer.print("非法请求。");
        }
    }
}
